package org.jflame.context.ratelimiter;

import org.jflame.context.cache.CacheWrapper;
import org.jflame.context.cache.GuavaWrapper;

import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.concurrent.EventCountCircuitBreaker;

/**
 * 基于{@link EventCountCircuitBreaker}实现的限速器,适用于单机
 * 
 * @author charles.zhang
 */
public class InMemoryRateLimiter implements RateLimiter {

    private CacheWrapper<String,EventCountCircuitBreaker> counterCache;

    public InMemoryRateLimiter() {
        this(new GuavaWrapper<>(100, 300));
    }

    /**
     * 构造函数
     * 
     * @param counterCache 断路器缓存,注:缓存过期时间应大于限速阀值检查时间
     */
    public InMemoryRateLimiter(CacheWrapper<String,EventCountCircuitBreaker> counterCache) {
        this.counterCache = counterCache;
    }

    @Override
    public boolean checkLimit(String requestId, int threshold, long intervalInSecond) {
        EventCountCircuitBreaker breaker = counterCache.get(requestId);
        if (breaker == null) {
            breaker = new EventCountCircuitBreaker(threshold, intervalInSecond, TimeUnit.SECONDS);
            counterCache.put(requestId, breaker);
            return true;
        }
        return !breaker.incrementAndCheckState();
    }

}
